package com.WOWTradeNews.DataBase;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class SystemDBManager{
	private Context mContext;
	private SystemDBHelper dbHelper;
	private SQLiteDatabase db;

	public SystemDBManager(Context context) {
		mContext = context;
		dbHelper = new SystemDBHelper(mContext, ConstValues.DB_SYSTEM);
		db = dbHelper.getWritableDatabase();
	}
	
	
	public int getMyCoin() {
		int coin = 0;
		
		Cursor cursor = db.rawQuery("SELECT * FROM myCoin", null);
		if(cursor.moveToFirst()) {
			coin = cursor.getInt(cursor.getColumnIndex("myCoin"));
		}
		cursor.close();
		
		return coin;
	}
	
	public void setMyCoin(int coin) {
		db.execSQL("UPDATE myCoin SET myCoin = ?",
				new String[]{String.valueOf(coin)});
	}
	
	public List<News> getMyFavoritesList() {
		List<News> list = new ArrayList<News>();
		Cursor cursor = db.rawQuery("SELECT * FROM myFavorites", null);
		
		while(cursor.moveToNext()) {
			String iid = cursor.getString(cursor.getColumnIndex("newsId"));
			DBManager dbManager = new DBManager(mContext, ConstValues.DB_NEWS);
			News news = dbManager.findByIid(iid);
			if(news == null) {
				news = new News();
				news.setGj(true);
			}
			news.setIid(iid);
			news.setNote(cursor.getString(cursor.getColumnIndex("note")));
			news.setGjtitle(cursor.getString(cursor.getColumnIndex("gjtitle")));
			news.setGjContent(cursor.getString(cursor.getColumnIndex("subject")));
			list.add(news);
		}
		cursor.close();
		
		return list;
	}
	
	public void addFavorites(String iid, String subject,String gjtitle) {
		db.execSQL("INSERT INTO myFavorites(newsId, subject,gjtitle) VALUES(?, ?, ?)", new String[]{iid, subject, gjtitle});
	}
	
	public void delateFavorites(String iid) {
		db.execSQL("DELATE myFavorites WHERE newsId=?", new String[]{iid});
	}
	
	public void updateFav(String note, String iid) {
		ContentValues cv = new ContentValues();
		cv.put("note", note);
		db.beginTransaction();
		db.update("myFavorites", cv, "newsId=?", new String[]{iid});
//		db.execSQL("UPDATE myFavorites SET note=? WHERE newsId=?", new String[]{note,iid});
		db.setTransactionSuccessful();
		db.endTransaction();
	}
	
	public boolean inMyFavoritesLsit(String iid) {  
		Cursor cursor = db.rawQuery("SELECT * FROM myFavorites WHERE newsId=?", new String[]{iid});
		boolean res = cursor.getCount() > 0;
		cursor.close();
		return res;
	}
	
	public String queryNote(String iid) {
		Cursor cursor = db.rawQuery("SELECT note FROM myFavorites WHERE newsId=?", new String[]{iid});
		String note = "";
		while(cursor.moveToNext()) {
			note = cursor.getString(0);
		}
		return note;
	}
	
	
	public void closeDB() {
		dbHelper.close();
		db.close();
	}
	
	

}
